package com.maserb.monitor.remote.client;

import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.springframework.beans.factory.annotation.Value;

import java.util.Random;

public class BrushCardServiceClient {

    @Value("${timeSpace.url}")
    private String url;
    @Value("${timeSpace.platformCode}")
    private String platform;


    public void invoke(String deviceNo) throws Exception {

        Integer sendBagNo = bagNo();
        Integer receiveBagNo = bagNo();

        Integer checkSum = 21 + sendBagNo + receiveBagNo + 2 + 1;        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
        Client client = dcf.createClient(url);


        StringBuilder text = new StringBuilder("UPO");
        text.append(platform);  //平台编号
        text.append(deviceNo); //设备编号
        text.append("0");  //无需接收确认
        text.append("21");  //功能编号
        text.append(sendBagNo.toString());  //发送包号
        text.append(receiveBagNo.toString());  //应答包号
        text.append("02");   //包长度
        text.append("01");  //包内容
        text.append(checkSumHexString(checkSum));  //校验和  功能号、发送包号、应答包号、包长度和包内容的和取低位两个字节


        Object[] objects = client.invoke("acceptBrushCard", "test");
        //输出调用结果
        System.out.println("*****" + objects[0].toString());
    }

    private Integer bagNo() {
        Random r = new Random();
        Integer tmp = r.nextInt(9999);
        String s = tmp.toString();

        for(int i=s.length(); i<4; i++) {
            s = "0" + s;
        }

        return Integer.valueOf(s);
    }

    private String checkSumHexString(int checkSum) {
        String hexString = Integer.toHexString(checkSum);

        if(hexString.length() >= 2) {
            return hexString.substring(hexString.length()-2, hexString.length());
        } else {
            return "0" + hexString;
        }
    }
}
